import axios from 'axios';
import { MODELScope_CONFIG } from '../config/modelscope';
import { EMOTION_ANALYSIS_PROMPT, IMAGE_GENERATION_PROMPT, EMOTION_BACKGROUND_MAPPING } from '../config/prompts';

// 通用API调用函数，包含重试机制
const callApiWithRetry = async (apiCall: () => Promise<any>, maxRetries = 3, delay = 1000) => {
  let lastError: any;

  for (let i = 0; i <= maxRetries; i++) {
    try {
      const response = await apiCall();
      return response;
    } catch (error: any) {
      lastError = error;
      console.error(`API调用失败 (尝试 ${i + 1}/${maxRetries + 1}):`, error.message || error);

      // 如果不是最后一次尝试，等待后重试
      if (i < maxRetries) {
        await new Promise(resolve => setTimeout(resolve, delay * Math.pow(2, i))); // 指数退避
      }
    }
  }

  throw lastError;
};

// 情绪分析服务 - 使用OpenAI兼容API
export const analyzeEmotion = async (text: string) => {
  try {
    // 构造增强版Prompt
    const enhancedPrompt = EMOTION_ANALYSIS_PROMPT.replace('{text}', text);

    const apiCall = () => axios.post(
      `${MODELScope_CONFIG.BASE_URL}chat/completions`,
      {
        model: MODELScope_CONFIG.EMOTION_ANALYSIS_MODEL,
        messages: [
          {
            role: "system",
            content: "你是一个专业的情感分析专家"
          },
          {
            role: "user",
            content: enhancedPrompt
          }
        ],
        stream: false
      },
      {
        headers: MODELScope_CONFIG.HEADERS
      }
    );

    const response = await callApiWithRetry(apiCall);
    return response.data;
  } catch (error: any) {
    console.error('情绪分析API调用失败:', error);
    throw new Error('情绪分析服务暂时不可用');
  }
};

// 文生图服务 - 使用异步任务模式
export const generateImage = async (prompt: string, emotion: string) => {
  try {
    // 构造增强版Prompt
    const enhancedPrompt = IMAGE_GENERATION_PROMPT
      .replace('{emotion}', emotion)
      .replace('{text}', prompt);

    // 添加情感背景特征
    const backgroundFeatures = EMOTION_BACKGROUND_MAPPING[emotion] || '';
    const finalPrompt = `${enhancedPrompt}\n情感背景特征：${backgroundFeatures}`;

    const apiCall = () => axios.post(
      `${MODELScope_CONFIG.BASE_URL}images/generations`,
      {
        model: MODELScope_CONFIG.TEXT_TO_IMAGE_MODEL,
        prompt: finalPrompt
      },
      {
        headers: {
          ...MODELScope_CONFIG.HEADERS,
          "X-ModelScope-Async-Mode": "true"
        }
      }
    );

    const response = await callApiWithRetry(apiCall);
    return response.data;
  } catch (error: any) {
    console.error('图片生成API调用失败:', error);
    throw new Error('图片生成服务暂时不可用');
  }
};

// 查询任务状态
export const getTaskStatus = async (taskId: string) => {
  try {
    // 添加任务类型头以查询图像生成任务
    const headersWithTaskType = {
      ...MODELScope_CONFIG.HEADERS,
      "X-ModelScope-Task-Type": "image_generation"
    };

    const apiCall = () => axios.get(
      `${MODELScope_CONFIG.BASE_URL}tasks/${taskId}`,
      {
        headers: headersWithTaskType
      }
    );

    const response = await callApiWithRetry(apiCall);
    return response.data;
  } catch (error: any) {
    console.error('任务状态查询失败:', error);
    throw new Error('任务状态查询失败');
  }
};